//
//  WBOAuthViewController.swift
//  WeiboSwift
//
//  Created by hfwd on 2017/5/24.
//  Copyright © 2017年 hfwd. All rights reserved.
//

import UIKit
import SVProgressHUD


/// 通过Webview加载授权登录界面
class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
  
    override func loadView() {
        super.loadView()
        
        //设置导航栏
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view = webView
        
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
        
        /// 加载授权界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURL)"
        
        let url = URL(string:urlString)
        
        let request = URLRequest(url: url!)
        
        webView.loadRequest(request)
    }
    
    //MARK: - 监听方法
    /// 导航栏左侧返回按钮监听事件
    func close() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    /// 导航栏右侧自动填充按钮监听事件
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '13530115467';" + "document.getElementById('passwd').value = '8624769xsc';"

        webView.stringByEvaluatingJavaScript(from: js)
    }
}

// MARK: - UIWebViewDelegate
extension WBOAuthViewController: UIWebViewDelegate {
    
    /// 将要加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let requestUrl = request.url?.absoluteString
        
        if requestUrl?.hasPrefix(WBRedirectURL) == false {
            
            return true
        }
        
        //取消授权
        if request.url?.query?.hasPrefix("code=") == false {
            
            close()
            
            return false
        }
        
        //获取授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        WBNetworkManager.shared.loadAccessTokenRequest(code: code) { (result, isSuccess) in
            
            if isSuccess {
                
                SVProgressHUD.showInfo(withStatus: WBNetWorkRequestSuccess)
                
                //切换主界面,发送登录成功通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
                
                self.close()
                
            } else {
                
                SVProgressHUD.showInfo(withStatus: WBNetWorkRequestFailure)
            }
        }
        
        return false
    }
}
